#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "mpi.h"

/**********************************************
 * \author James Edmondson
 * \brief Tests the MPI_Reduce function. I believe this was
 *        started by Vijay, but I rewrote almost all of it.
 **********************************************/

int main(int argc, char **argv)
{
	int size, rank, total = 0;

	int sendbuf[2];
	int recvbuf[2] = {-1,-1};
	int i = 0;
	
	MPI_Init(&argc, &argv);
	
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);

	
	printf("Size %d, Rank %d\n",size,rank);

	for( i = 1; i < size; i++ )
	{
		total += i;
	}

	sendbuf[0] = rank;
	sendbuf[1] = rank;
	
	if( rank == 0 )
	{
		printf("ALLREDUCE Op=MPI_SUM Type=MPI_INT\n");
		printf("ALLREDUCE ROOT BEFORE: send[0]=%d, send[1]=%d\n",
				sendbuf[0],sendbuf[1]);
		printf("ALLREDUCE ROOT BEFORE: recv[0]=%d, recv[1]=%d\n",
				recvbuf[0],recvbuf[1]);
		MPI_Allreduce(sendbuf,recvbuf,2,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
		printf("ALLREDUCE ROOT AFTER: recv[0]=%d, recv[1]=%d\n",
				recvbuf[0],recvbuf[1]);

		if( recvbuf[0] == total && recvbuf[1] == total )
		{
			printf("SUCCESS\n");
		}
		else
		{
			printf("FAILURE\n");
		}
	}
	else 
	{
		printf("ALLREDUCE BEFORE: send[0]=%d, send[1]=%d\n",
				sendbuf[0],sendbuf[1]);
		printf("ALLREDUCE BEFORE: recv[0]=%d, recv[1]=%d\n",
				recvbuf[0],recvbuf[1]);
		MPI_Allreduce(sendbuf,recvbuf,2,MPI_INT,MPI_SUM,MPI_COMM_WORLD);
		printf("ALLREDUCE AFTER: recv[0]=%d, recv[1]=%d\n",
				recvbuf[0],recvbuf[1]);

		if( recvbuf[0] == total && recvbuf[1] == total )
		{
			printf("SUCCESS\n");
		}
		else
		{
			printf("FAILURE\n");
		}
	}
	
	
	MPI_Finalize();
	return 0;
}

